﻿using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.IO;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class AttmentController : Base
{
   private readonly ApplicationContext _applicationContext;
    private readonly AttmentService _attment;
    public AttmentController(ApplicationContext applicationContext, AttmentService attmentService)
    {
        _applicationContext = applicationContext;
        _attment = attmentService;
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Attment_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] AttmentQuery parm)
    {
        ILoginUserInfo adminUser = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        parm.Uid = adminUser.GroupId != 1 ? adminUser.UserId : 0;//超级管理员显示全部数据
        if (parm.ExportExcel)
        {
            PagedInfo<ViewAttment> list = await _attment.GetPageListAsync(parm);
            string sFileName = ExcelHelperAction.ExportExcel(list.Result, "附件列表");
            return Success(new { FilePath = "/export/" + sFileName, fileName = sFileName });
        }
        else
        {
            PagedInfo<ViewAttment> list = await _attment.GetPageListAsync(parm);
            return Success(list);
        }
    }

    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Attment_Delete)]
    [Log(Name = "删除上传文件")]
    public async Task<IActionResult> DeleteAsync(int id)
    {
        Attment attment = await _attment.GetIdAsync(id);
        string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot") + "\\" + attment.Url;
        if (FileUtility.FileExists(filePath))
            FileUtility.FileDel(filePath);
        if (await _attment.DeleteAsync(id) > 0)
            return Success("删除上传文件 id:" + id);
        else
            return Fail("删除上传文件 id:" + id);
    }
}
